package com.sgb.kjwl.view.ui.activity.leaseAsk.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;

import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAskLeaseFactoryBinding;
import com.sgb.kjwl.di.machine.DaggerMachineComponent;
import com.sgb.kjwl.di.machine.MachineModule;
import com.sgb.kjwl.model.entity.AskLeaseFactoryEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.machine.AskLeaseFactoryModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

/**
 * 工厂求租发布
 */
public class AskLeaseFactoryActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    @Inject
    AskLeaseFactoryModel viewModel;
    private ActivityAskLeaseFactoryBinding binding;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Calendar selectedDate = Calendar.getInstance();
    private Calendar selectedDate2 = Calendar.getInstance();

    private List<PickSelectEntity> classDatas;
    private List<List<PickSelectEntity>> typeDatas;
    private List<DictEntity3> powerDatas = new ArrayList<>();
    private List<DictEntity3> hasNotList = new ArrayList<>();//区域列表
    private List<DictEntity3> allpayway = new ArrayList<>();//支付方式列表
    private List<UnitEntity> priceUnit = new ArrayList<>();//价格单位列表
    private AskLeaseFactoryEntity askLeaseFactoryEntity = new AskLeaseFactoryEntity();
    private String id = "";

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMachineComponent.builder().appComponent(appComponent)
                .machineModule(new MachineModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent(context, AskLeaseFactoryActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_ask_lease_factory);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("工厂求租发布");
        binding.topLayout.ivBack.setOnClickListener(v -> finish());
        //立即发布按钮
        binding.publicView.setOnClickListener(v -> publishAskLeaseData());
        binding.include.tvUse.setOnClickListener(v -> binding.include.itemTvTitleEdit.setEditContent(binding.include.tvTitleDefault.getText().toString()));
        binding.itvType.setOnWholeItemClickListener(this);
        binding.area.setOnWholeItemClickListener(this);
        binding.address.setOnWholeItemClickListener(this);
        binding.itvWater.setOnWholeItemClickListener(this);
        binding.itvElectricity.setOnWholeItemClickListener(this);
        binding.itvOffice.setOnWholeItemClickListener(this);
        binding.itvAccommodation.setOnWholeItemClickListener(this);
        binding.itvCargoPlatform.setOnWholeItemClickListener(this);
        binding.itvParking.setOnWholeItemClickListener(this);
        binding.timeCourse.setOnWholeItemClickListener(this);
        binding.timeDeadline.setOnWholeItemClickListener(this);
        binding.paymentMethod.setOnWholeItemClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_PHONE);
        binding.leaseTime.setFilters(new EditInputFilter[]{new EditInputFilter(9999999, 1, 0)});
        binding.houseArea.setFilters(new EditInputFilter[]{new EditInputFilter(9999999.99, 2)});
        binding.leasePrice.setFilters(new EditInputFilter[]{new EditInputFilter(99999999.99, 2)});
        binding.itvFirstHeight.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itvFirstHeight.setCheck(2, 2);
        // 面议还是报价功能
        binding.rbTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutDays.setVisibility(View.GONE);
                    binding.rbTime.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutDays.setVisibility(View.VISIBLE);
                    binding.rbTime.setText("面议");
                }
            }
        });
        //   面议还是报价功能
        binding.rbPrice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
                    binding.layoutPrice.setVisibility(View.GONE);
                    binding.rbPrice.setText("您已选择面议，再次点击退出面议");
                } else {
                    binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
                    binding.layoutPrice.setVisibility(View.VISIBLE);
                    binding.leasePrice.setText("");
                    binding.leasePrice.setHint("请输入(必填)");
                    binding.rbPrice.setText("面议");
                }
            }
        });
        //        租赁价格展示
        binding.tvPriceUnit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                hideKeyboard(binding.tvPriceUnit);
                setSoftWareHide();
                PriceUnitData();
            }
        });

        binding.houseArea.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setDefaultTitle();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void init() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);

        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        classDatas = new ArrayList<>();
        typeDatas = new ArrayList<>();
        allpayway = new ArrayList<>();

        viewModel.getAddressModel();//请求省市区数据
        viewModel.getTypeModel();//数据类型
        viewModel.getAllPayWay();//付款方式
        viewModel.getPowerWay();//供电方式
        viewModel.getHasNotConfig();
        viewModel.getPriceUnitModel();//租赁单位
        id = getIntent().getStringExtra("id");
        if (!TextUtils.isEmpty(id)) {
            viewModel.getDetail(id);
        }

    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_type://租赁类型
                if (classDatas.size() != 0) {
                    showClassTypePop();
                }
                break;
            case R.id.area://所在地址
                if (addressEntityList != null) {
                    showCityPop("请选择地区");
                }
                break;
            case R.id.address:
                if (!TextUtils.isEmpty(binding.area.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(askLeaseFactoryEntity.getProvinceNo(), askLeaseFactoryEntity.getCityNo(), askLeaseFactoryEntity.getAreaNo());
                } else {
                    MToast.showToast(this, "请选择使用地区");
                }
                break;
            case R.id.time_course://使用时间(进场时间)
                showCourseTimePop();
                break;
            case R.id.time_deadline://报价截止时间
                if (TextUtils.isEmpty(binding.timeCourse.getContent())) {
                    MToast.showToast(this, "请选择使用时间");
                    return;
                } else {
                    showLimitTimePop();
                }
                break;
            case R.id.payment_method://付款方式选择
                showPaymentMethodPop();
                break;
            case R.id.itv_water://供水情况
                showWaterPop();
                break;
            case R.id.itv_electricity://供电情况
                showElectriPop();
                break;
            case R.id.itv_office://办公区域
                showOfficePop();
                break;
            case R.id.itv_accommodation://住宿区域
                showAccommodationPop();
                break;
            case R.id.itv_cargo_platform://卸货平台
                showLandingPlatformPop();
                break;
            case R.id.itv_parking://停车区域
                showParkingPop();
                break;
            default:
                break;
        }
    }

    //付款方式选择
    private void showPaymentMethodPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = allpayway.get(options1).getName();
            askLeaseFactoryEntity.setRentalPayMethod(allpayway.get(options1).getId());
            askLeaseFactoryEntity.setRentalPayMethodName(allpayway.get(options1).getPickerViewText());
            binding.paymentMethod.setContent(content);
        }).build();
        businessOption.setPicker(allpayway);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //供水情况
    private void showWaterPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = powerDatas.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setWaterSupply(powerDatas.get(options1).getId());
            askLeaseFactoryEntity.setWaterSupplyName(powerDatas.get(options1).getPickerViewText());
            binding.itvWater.setContent(content);
        }).build();
        businessOption.setPicker(powerDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //供电情况
    private void showElectriPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = powerDatas.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setPowerSupply(powerDatas.get(options1).getId());
            askLeaseFactoryEntity.setPowerSupplyName(powerDatas.get(options1).getPickerViewText());
            binding.itvElectricity.setContent(content);
        }).build();
        businessOption.setPicker(powerDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //办公区域
    private void showOfficePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = hasNotList.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setOfficeArea(hasNotList.get(options1).getId());
            askLeaseFactoryEntity.setOfficeAreaName(hasNotList.get(options1).getPickerViewText());
            binding.itvOffice.setContent(content);
        }).build();
        businessOption.setPicker(hasNotList);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //停车区域
    private void showParkingPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = hasNotList.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setParkingArea(hasNotList.get(options1).getId());
            askLeaseFactoryEntity.setParkingAreaName(hasNotList.get(options1).getPickerViewText());
            binding.itvParking.setContent(content);
        }).build();
        businessOption.setPicker(hasNotList);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //住宿区域
    private void showAccommodationPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = hasNotList.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setAccommodationArea(hasNotList.get(options1).getId());
            askLeaseFactoryEntity.setAccommodationAreaName(hasNotList.get(options1).getPickerViewText());
            binding.itvAccommodation.setContent(content);
        }).build();
        businessOption.setPicker(hasNotList);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //卸货平台
    private void showLandingPlatformPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = hasNotList.get(options1).getPickerViewText();
            askLeaseFactoryEntity.setLandingPlatform(hasNotList.get(options1).getId());
            askLeaseFactoryEntity.setLandingPlatformName(hasNotList.get(options1).getPickerViewText());
            binding.itvCargoPlatform.setContent(content);
        }).build();
        businessOption.setPicker(hasNotList);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }


    //使用时间
    private void showCourseTimePop() {
        Calendar dayCalendar = Calendar.getInstance();
        dayCalendar.setTime(new Date());
        dayCalendar.add(Calendar.DAY_OF_MONTH, 1);

        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            try {
                binding.timeCourse.setContent(format);
                askLeaseFactoryEntity.setUseAndEnterTime(DateUtils.dateTo13Timestamp(format + " 23:59:59") + "");
                selectedDate2.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(dayCalendar, null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate2);
    }

    //报价截止时间
    private void showLimitTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(this, (date, v) -> {
            try {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                if (checkDate(format, binding.timeCourse.getContent())) {
                    return;
                }
                askLeaseFactoryEntity.setEndTime(DateUtils.dateTo13Timestamp3(format + " 23:59:59") + "");
                binding.timeDeadline.setContent(format);
                selectedDate.setTime(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择时间")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setRangDate(Calendar.getInstance(), null)
                .build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    //日期比较
    private boolean checkDate(String startTime, String endTime) {
        try {
            if (DateUtils.dateTo13Timestamp(endTime) < DateUtils.dateTo13Timestamp(startTime) || startTime.equals(endTime)) {
                MToast.showToast(this, "请选择小于使用时间的日期");
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }

    //    选择地址弹窗
    private void showCityPop(String title) {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                }
                String content = addressEntityList.get(options1).getName() + " / " + opt2.get(options1).get(options2).getName() + " / " + areaName;
                cityPosition1 = options1;
                cityPosition2 = options2;
//                rentAddress = new PublishLeaseDataEntity.RentAddress();
//                if (!TextUtils.isEmpty(areaName)) {
//                    rentAddress.setAreaId(opt3.get(options1).get(options2).get(options3).getNo());
//                }
                askLeaseFactoryEntity.setProvinceNo(addressEntityList.get(options1).getNo());
                askLeaseFactoryEntity.setCityNo(opt2.get(options1).get(options2).getNo());
                askLeaseFactoryEntity.setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
//                Log.d("地址：", content);
//                rentAddress.setRentalAddress(content);

                binding.area.setContent(content);
                binding.address.setContent("");
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText(title)
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //返回省市区数据加载数据
    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        addressEntityList = data;
        initJsonData();
    }

    //组装省市区数据信息
    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    //发布数据
    private void publishAskLeaseData() {
        if (TextUtils.isEmpty(binding.itvType.getContent())) {
            MToast.showToast(this, "请选择租赁分类");
            return;
        }
        if (TextUtils.isEmpty(binding.houseArea.getText().toString())) {
            MToast.showToast(this, "请输入租赁面积");
            return;
        }
        if (Double.parseDouble(binding.houseArea.getText().toString()) <= 0) {
            MToast.showToast(this, "请输入正确的租赁面积");
            return;
        }
        if (TextUtils.isEmpty(binding.area.getContent())) {
            MToast.showToast(this, "请选择使用地区");
            return;
        }
        if (TextUtils.isEmpty(binding.address.getContent())) {
            MToast.showToast(this, "请选择详细地址");
            return;
        }
        if (TextUtils.isEmpty(binding.timeCourse.getContent())) {
            MToast.showToast(this, "请选择使用时间");
            return;
        }
        if (TextUtils.isEmpty(binding.timeDeadline.getContent())) {
            MToast.showToast(this, "请选择报价截止时间");
            return;
        }
        if (!TextUtils.isEmpty(binding.itvFirstHeight.getContent())) {
            if (Double.parseDouble(binding.itvFirstHeight.getContent()) > 50) {
                MToast.showToast(this, "首层层高不能大于50");
                return;
            } else if (Double.parseDouble(binding.itvFirstHeight.getContent()) <= 0) {
                MToast.showToast(this, "首层层高不能小于0");
                return;
            }
        }
        if (TextUtils.isEmpty(binding.itvPurpose.getContent())) {
            MToast.showToast(this, "请输入厂房用途");
            return;
        }
        if (TextUtils.isEmpty(binding.itvWater.getContent())) {
            MToast.showToast(this, "请选择供水情况");
            return;
        }
        if (TextUtils.isEmpty(binding.itvElectricity.getContent())) {
            MToast.showToast(this, "请选择供电情况");
            return;
        }
        if (TextUtils.isEmpty(binding.itvOffice.getContent())) {
            MToast.showToast(this, "请选择办公区域");
            return;
        }
        if (TextUtils.isEmpty(binding.itvAccommodation.getContent())) {
            MToast.showToast(this, "请选择住宿区域");
            return;
        }
        if (TextUtils.isEmpty(binding.itvCargoPlatform.getContent())) {
            MToast.showToast(this, "请选择卸货平台");
            return;
        }
        if (TextUtils.isEmpty(binding.itvParking.getContent())) {
            MToast.showToast(this, "请选择停车区域");
            return;
        }
        if (TextUtils.isEmpty(binding.paymentMethod.getContent())) {
            MToast.showToast(this, "请选择付款方式");
            return;
        }
        if (TextUtils.isEmpty(binding.leaseUsername.getContent())) {
            MToast.showToast(this, "请填写联系人");
            return;
        }
        if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
            MToast.showToast(this, "请填写联系电话");
            return;
        }
        if (!CheckUtils.isPhoneNumberValid(binding.itemTvPhone.getContent())) {
            MToast.showToast(this, "请填写正确的联系电话");
            return;
        }

        if (checkDate(binding.timeDeadline.getContent(), binding.timeCourse.getContent())) {
            return;
        }

        if (binding.rbTime.isChecked()) {
            askLeaseFactoryEntity.setRentalDuration("-1");
        } else {
            if (TextUtils.isEmpty(binding.leaseTime.getText().toString())) {
                MToast.showToast(this, "请填写租赁时长");
                return;
            }
            askLeaseFactoryEntity.setRentalDuration(binding.leaseTime.getText().toString());
        }
        if (binding.rbPrice.isChecked()) {
            askLeaseFactoryEntity.setRentalPrice("-1");
        } else {
            if (TextUtils.isEmpty(binding.leasePrice.getText().toString())) {
                MToast.showToast(this, "请填写期望租金");
                return;
            }
            if (Double.parseDouble(binding.leasePrice.getText().toString()) <= 0) {
                MToast.showToast(this, "请填写大于0的期望租金");
                return;
            }
            askLeaseFactoryEntity.setRentalPrice(binding.leasePrice.getText().toString() + "");
        }

        // 详细地址
        askLeaseFactoryEntity.setTaskAddr(binding.address.getContent());
        askLeaseFactoryEntity.setFirstFloorHeight(binding.itvFirstHeight.getContent());
        askLeaseFactoryEntity.setFactoryUse(binding.itvPurpose.getContent());
        askLeaseFactoryEntity.setContactPerson(binding.leaseUsername.getContent());
        askLeaseFactoryEntity.setContactPhone(binding.itemTvPhone.getContent());
        askLeaseFactoryEntity.setRemark(binding.leaseExpand.getEditContent());
        askLeaseFactoryEntity.setRentalArea(binding.houseArea.getText().toString());
        //设置标题参数
        if (!TextUtils.isEmpty(binding.include.itemTvTitleEdit.getEditContent())) {
            askLeaseFactoryEntity.setTitle(binding.include.itemTvTitleEdit.getEditContent());
        } else {
            MToast.showToast(this, "请填写标题");
            return;
        }

        viewModel.addOrupdate(askLeaseFactoryEntity);
    }

    //租赁单位
    private void PriceUnitData() {
        OptionsPickerView build = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String content = priceUnit.get(options1).getName();
            String no = priceUnit.get(options1).getNo();
            binding.tvPriceUnit.setText(content);
            askLeaseFactoryEntity.setPriceUnitNo(no);
            askLeaseFactoryEntity.setPriceUnitName(content);
        }).build();
        build.setPicker(priceUnit);
        build.setSelectOptions(0);
        build.show();
    }

    //分类
    private void showClassTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String className = classDatas.get(options1).getProjectscale();
            askLeaseFactoryEntity.setFirstCategoryNo(classDatas.get(options1).getNo());
            binding.itvType.setContent(className);
            setDefaultTitle();
        }).build();
        businessOption.setPicker(classDatas);
        businessOption.setSelectOptions(0);
        businessOption.show();
    }

    //租赁单位选择
    public void setEstatePriceUnit(List<UnitEntity> list) {
        this.priceUnit = list;
        if (list.size() > 0) {
            binding.tvPriceUnit.setText(list.get(0).getName());
            askLeaseFactoryEntity.setPriceUnitNo(list.get(0).getNo());
            askLeaseFactoryEntity.setPriceUnitName(list.get(0).getName());
        }
    }

    //类型集合
    public void showTypeView(List<AskLeaseItemEntity<List<AskLeaseItemEntity>>> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : data) {
            PickSelectEntity entity = new PickSelectEntity();
            entity.setNo(l.getNo());
            entity.setProjectscale(l.getName());
            classDatas.add(entity);
//            List<PickSelectEntity> childList = new ArrayList<>();
//            for (AskLeaseItemEntity ll : l.getChildren()) {
//                PickSelectEntity child = new PickSelectEntity();
//                child.setNo(ll.getNo());
//                child.setProjectscale(ll.getName());
//                childList.add(child);
//            }
//            typeDatas.add(childList);
        }
    }

    //获取办公区域、停车区域、住宿区域、卸货平台配置信息
    public void showPurposeList(List<DictEntity3> data) {
        this.hasNotList = data;
    }

    //供水供电方式
    public void showPowerWay(List<DictEntity3> data) {
        this.powerDatas = data;
    }

    // 付款方式
    public void showAllPayWay(List<DictEntity3> data) {
        this.allpayway = data;
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        askLeaseFactoryEntity.setLatitude(data.getLat());
        askLeaseFactoryEntity.setLongitude(data.getLng());
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 255) {
                if (data == null) {
                    return;
                }
                double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
                double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
                String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
                askLeaseFactoryEntity.setLatitude(lat + "");
                askLeaseFactoryEntity.setLongitude(lon + "");
                binding.address.setContent(address + "");
            }

        }
    }

    //动态设置设置默认标题
    private void setDefaultTitle() {
        if (!TextUtils.isEmpty(binding.houseArea.getText())) {
            binding.include.tvTitleDefault.setText("求租" + binding.itvType.getContent() + "/" + binding.houseArea.getText().toString() + "㎡");
        } else {
            binding.include.tvTitleDefault.setText("求租" + binding.itvType.getContent());
        }
        binding.include.rlLeaseTitle.setVisibility(View.VISIBLE);
    }

    /**
     * 编辑回显 使用
     *
     * @param entity
     */
    public void showDetail(AskLeaseFactoryEntity entity) {
        this.askLeaseFactoryEntity = entity;

        binding.itvType.setContent(entity.getFirstCategoryName());
        binding.houseArea.setText(entity.getRentalArea());
        binding.leaseUsername.setContent(entity.getContactPerson());
        binding.itemTvPhone.setContent(entity.getContactPhone());
        binding.timeCourse.setContent(DateUtils.stampToDay(entity.getUseAndEnterTime()));
        binding.timeDeadline.setContent(DateUtils.stampToDay(entity.getEndTime()));
        binding.area.setContent(entity.getCityName() + entity.getAreaName());
        binding.address.setContent(entity.getTaskAddr());
        binding.itvFirstHeight.setContent(entity.getFirstFloorHeight());//首层层高
        binding.itvPurpose.setContent(entity.getFactoryUse());//工厂用途
        binding.itvWater.setContent(entity.getWaterSupplyName());
        binding.itvElectricity.setContent(entity.getPowerSupplyName());
        binding.itvOffice.setContent(entity.getOfficeAreaName());//办公区域
        binding.itvAccommodation.setContent(entity.getAccommodationAreaName());//住宿区域
        binding.itvCargoPlatform.setContent(entity.getLandingPlatformName());//卸货平台
        binding.itvParking.setContent(entity.getParkingAreaName());//停车区域
        binding.paymentMethod.setContent(entity.getRentalPayMethodName());
        binding.include.itemTvTitleEdit.setEditContent(entity.getTitle());
        binding.leaseExpand.setEditContent(entity.getRemark());

        if (!TextUtils.isEmpty(entity.getRentalDuration()) && (Double.parseDouble(entity.getRentalDuration()) >= 0)) {
            binding.leaseTime.setText(entity.getRentalDuration());
            binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_unselect);
            binding.layoutDays.setVisibility(View.VISIBLE);
            binding.rbTime.setText("面议");
            askLeaseFactoryEntity.setRentalDuration(entity.getRentalDuration());
            binding.rbTime.setChecked(false);
        } else {
            binding.rbTime.setButtonDrawable(R.mipmap.lease_pub_select);
            binding.layoutDays.setVisibility(View.GONE);
            askLeaseFactoryEntity.setRentalDuration("-1");
            binding.rbTime.setText("您已选择面议，再次点击退出面议");
            binding.rbTime.setChecked(true);
        }
        if (Double.parseDouble(entity.getRentalPrice()) >= 0) {
            binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_unselect);
            binding.rbPrice.setChecked(false);
            binding.layoutPrice.setVisibility(View.VISIBLE);
            binding.rbPrice.setText("面议");
            binding.leasePrice.setText(entity.getRentalPrice());
            binding.tvPriceUnit.setText(entity.getPriceUnitName());
        } else {
            binding.rbPrice.setChecked(true);
            binding.rbPrice.setButtonDrawable(R.mipmap.lease_pub_select);
            binding.layoutPrice.setVisibility(View.GONE);
            binding.rbPrice.setText("您已选择面议，再次点击退出面议");
        }

        //旧版本面议的会导致价格单位为空,则默认一个
        if (TextUtils.isEmpty(binding.tvPriceUnit.getText())) {
            binding.tvPriceUnit.setText(priceUnit.get(0).getName());
            askLeaseFactoryEntity.setPriceUnitNo(priceUnit.get(0).getNo());
            askLeaseFactoryEntity.setPriceUnitName(priceUnit.get(0).getName());
        }

    }

    /**
     * 隐藏软键盘
     */
    private void setSoftWareHide() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}
